import os
import socket


def get_host_ip() -> str:
    """
    查询本机ip地址
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("223.5.5.5", 80))
        ip = s.getsockname()[0]
    except:
        ip = '0.0.0.0'
    finally:
        s.close()

    return ip


def start_django():
    "开启django服务"
    # ip = get_host_ip()
    # 先更新依赖
    #cmd = "python3 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -U -r requirements.txt --break-system-packages"
    #os.system(cmd)
    # 使用gunicorn部署
    cmd = f"nohup gunicorn teachzero.wsgi:application --bind 0.0.0.0:12345 --workers 2 --worker-class=gevent >> ~/django_log.txt &"  
    # cmd = f"nohup python3 manage.py runserver {ip}:12345 --noreload --nothreading > ~/django_log.txt &"
    os.system(cmd)


def start_sync():
    """开启同步服务"""
    cmd = f"nohup python3 start_sync.py > ~/sync_log.txt &"
    os.system(cmd)


if __name__ == "__main__":
    path = os.path.dirname(__file__)
    path = os.path.abspath(path)
    #print(path)
    os.chdir(path)
    #start_sync()
    start_django()
